#include "StdAfx.h"
#include <stdlib.h>
#include "Cinterleaver.h"

CInterleaver::CInterleaver()
{
	mInterleaveIndex = NULL;
	mDeInterleaveIndex = NULL;
	mSize = 0;        
}

CInterleaver::~CInterleaver(void)
{
    if(mInterleaveIndex!=NULL){
        delete mInterleaveIndex;
    }

	if(mDeInterleaveIndex!=NULL){
        delete mDeInterleaveIndex;
    }
}

bool 
CInterleaver::Interleave(CMessage &msg)
{
    bool* boolmsg = msg.GetBoolMessage();
	double* noisymsg = msg.GetDoubleNoisyMessage();

    if(msg.GetSize()>mSize){ //interleaver is too short to interleave
        return false;
    }
    bool* int_msg = new bool[msg.GetSize()];
	if(int_msg==NULL){
        return false;
    }
	double* int_double_msg = new double[msg.GetSize()];
	if(int_double_msg==NULL){
		delete int_msg;
        return false;
    }

  
    for(uint32_t i=0;i<msg.GetSize();i++){
        int_msg[mInterleaveIndex[i]] = boolmsg[i];
		int_double_msg[mInterleaveIndex[i]] = noisymsg[i];
    }
    msg.Replace(int_msg,msg.GetSize());
	msg.Replace(int_double_msg,msg.GetSize());
    delete int_msg;
	delete int_double_msg;
    return true;
}

bool
CInterleaver::DeInterleave(CMessage &msg)
{
    bool* boolmsg = msg.GetBoolMessage();
	double* noisymsg = msg.GetDoubleNoisyMessage();

    if(msg.GetSize()>mSize){ //interleaver is too short to interleave
        return false;
    }
    bool* int_msg = new bool[msg.GetSize()];
	if(int_msg==NULL){
        return false;
    }
	double* int_double_msg = new double[msg.GetSize()];
	if(int_double_msg==NULL){
		delete int_msg;
        return false;
    }
  
    for(uint32_t i=0;i<msg.GetSize();i++){
        int_msg[mDeInterleaveIndex[i]] = boolmsg[i];
		int_double_msg[mDeInterleaveIndex[i]] = noisymsg[i];
    }
    msg.Replace(int_msg,msg.GetSize());
	msg.Replace(int_double_msg,msg.GetSize());
    delete int_msg;
	delete int_double_msg;
    return true;
}

bool 
CInterleaver::Interleave(double* arry, uint32_t size)
{
    
    if(size>mSize){ //interleaver is too short to interleave
        return false;
    }
    double* aux = new double[size];
    if(aux==NULL){
        return false;
    }
    for(uint32_t i=0;i<size;i++){
        aux[mInterleaveIndex[i]] = arry[i];
    }
	for(uint32_t i=0;i<size;i++){
        arry[i] = aux[i];
    }    
    delete aux;
    return true;
}

bool
CInterleaver::DeInterleave(double* arry, uint32_t size)
{
    if(size>mSize){ //interleaver is too short to interleave
        return false;
    }
    double* aux = new double[size];
    if(aux==NULL){
        return false;
    }
    for(uint32_t i=0;i<size;i++){
        aux[mDeInterleaveIndex[i]] = arry[i];
    }
	for(uint32_t i=0;i<size;i++){
        arry[i] = aux[i];
    }    
    delete aux;
    return true;
}